<template>
  <je-modal
    v-model:visible="visible"
    class="childfuncfield-select-func"
    width="600px"
    :title="title"
    height="auto"
    :resize="false"
    :maximizable="false"
    cancel-button
    :ok-button="handleOk"
    @close="handleClose"
  >
    <je-form
      ref="formRef"
      class="form"
      :rules="rules"
      :model="formState"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      autocomplete="off"
    >
      <je-form-item label="目标功能" name="code">
        <je-input v-model:value="formState.code" @click="SelectChildrenFunction">
          <template #suffix>
            <i class="icon-button fas fa-list-ul" @click="SelectChildrenFunction"></i
          ></template>
        </je-input>
        <!-- <GridSelect
          v-model:value="formState.code"
          config-info="JE_CORE_FUNCINFO,code~id,FUNCINFO_FUNCCODE~JE_CORE_FUNCINFO_ID,S"
          :querys="[
            {
              type: '=',
              code: 'SY_JESYS',
              value: '1',
            },
            {
              code: 'SY_PARENTPATH',
              type: 'like',
              value: formState.RESOURCEFIELD_FUNCINFO_ID,
              cn: 'and',
            },
            {
              code: 'FUNCINFO_NODEINFOTYPE',
              type: '=',
              value: 'FUNCFIELD',
              cn: 'and',
            },
          ]"
        /> -->
      </je-form-item>
      <je-form-item label="功能外键编码" name="fkName">
        <GridSelect
          v-model:value="formState.fkName"
          config-info="JE_CORE_RESOURCECOLUMN,fkName,RESOURCECOLUMN_CODE,S"
          :querys="[
            {
              code: 'RESOURCECOLUMN_FUNCINFO_ID',
              type: '=',
              value: formState.id,
              cn: 'and',
            },
          ]"
          @beforeSelect="beforeSelect"
        />
      </je-form-item>
      <je-form-item label="显示最大条数" name="number">
        <je-input-number v-model:value="formState.number" style="width: 100%" :min="0" />
      </je-form-item>
      <je-form-item label="主子传值" name="transferValue ">
        <je-textarea v-model:value="formState.transferValueCode" :rows="4">
          <template #suffix>
            <i
              class="fas fa-list-ul"
              style="color: rgba(0, 0, 0, 0.45); cursor: pointer; transition: all 0.3s"
              @click="getTransferValue"
            ></i>
          </template>
        </je-textarea>
      </je-form-item>
    </je-form>
  </je-modal>
</template>

<script>
  import { ref, toRefs, reactive, defineComponent, onMounted, h } from 'vue';
  import { Form, Modal, InputSelect, InputNumber, Input } from '@jecloud/ui';
  import MasterChildTransferValue from './master-child-transfer-value.vue';
  import { getData as GetFuncDetail, getSubChildList } from '@/api/index';
  import { SelectWindow } from '@jecloud/func';
  import { encode } from '@jecloud/utils';

  export default defineComponent({
    name: 'ChildFuncFieldSelectFunc',
    components: {
      JeModal: Modal,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInputNumber: InputNumber,
      GridSelect: InputSelect.Grid,
      JeInput: Input,
      JeTextarea: Input.TextArea,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
      recordData: {
        type: Object,
        default: () => {},
      },
      tableData: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['changeModal'],
    setup(props, { emit }) {
      const state = reactive({
        visible: props.visble,
        title: props.recordData.title,
        formRef: ref(),
        formState: props.recordData,
        labelCol: {
          style: { width: '150px' },
        },
        wrapperCol: {},
        rules: {
          code: [{ required: true, message: '请输入目标功能' }],
          fkName: [{ required: true, message: '请输入功能外键编码' }],
          number: [{ required: true, message: '请输入显示最大条数', trigger: 'change' }],
        },
      });

      const methods = {
        // 当表单字段是子功能集合的时候，点击目标功能获取数据
        SelectChildrenFunction() {
          // 对于表单字段，选择子功能集合类型，获取配置信息里面的值
          const SubChildrenList = (props.tableData || []).filter(
            (item) => item.RESOURCEFIELD_XTYPE == 'childfuncfield',
          );
          const checkSubChildrenId = [];
          SubChildrenList.map((item) => {
            const { RESOURCEFIELD_CONFIGINFO } = item;
            if (!RESOURCEFIELD_CONFIGINFO) return;
            checkSubChildrenId.push(RESOURCEFIELD_CONFIGINFO.split(',')[0]);
          });
          const params = {
            funcId: state.formState.RESOURCEFIELD_FUNCINFO_ID,
            page: 1,
            limit: 50,
            start: 0,
          };
          getSubChildList(params).then((res) => {
            const data = res.data.rows || [];
            const InSubChildren = [];
            if (data.length) {
              data.map((item) => {
                !checkSubChildrenId.includes(item.FUNCINFO_FUNCCODE) &&
                  InSubChildren.push(item.JE_CORE_FUNCINFO_ID);
              });
            }
            SelectWindow.show({
              title: '选中子功能集合',
              type: 'grid',
              configInfo: 'JE_CORE_FUNCINFO,,,S',
              querys: [
                {
                  type: '=',
                  code: 'SY_JESYS',
                  value: '1',
                },
                {
                  code: 'JE_CORE_FUNCINFO_ID',
                  value: InSubChildren,
                  type: 'in',
                  cn: 'and',
                },
                // {
                //   code: 'SY_PARENTPATH',
                //   type: 'like',
                //   value: state.formState.RESOURCEFIELD_FUNCINFO_ID,
                //   cn: 'and',
                // },
                {
                  code: 'FUNCINFO_NODEINFOTYPE',
                  type: '=',
                  value: 'FUNCFIELD',
                  cn: 'and',
                },
              ],
              callback: function ({ rows }) {
                if (!rows.length) {
                  return false;
                }
                const { FUNCINFO_FUNCCODE, JE_CORE_FUNCINFO_ID } = rows[0];
                state.formState.code = FUNCINFO_FUNCCODE;
                state.formState.id = JE_CORE_FUNCINFO_ID;
              },
            });
          });
        },
        handleClose() {
          state.visible = false;
          emit('changeModal', { isShow: false });
        },

        // 选择查询字段和展示字段的时候，判断一下目标功能是不是有值
        beforeSelect() {
          if (!state.formState.code) {
            Modal.alert('请先选择目标功能！');
            return false;
          }
          return true;
        },

        handleOk() {
          state.formRef
            .validate()
            .then(() => {
              methods.handleSave();
            })
            .catch((error) => {
              console.error(error);
            });
          return false;
        },

        handleSave() {
          let { code, fkName, number, transferValueCode } = state.formState;

          let cfgs = `${code},${fkName},${number},${transferValueCode}`;

          state.visible = false;
          emit('changeModal', {
            type: 'ChildFuncFieldSelectFunc',
            visible: false,
            data: {
              RESOURCEFIELD_CONFIGINFO: cfgs,
            },
          });

          return false;
        },

        getFuncDetail() {
          const params = {
            tableCode: 'JE_CORE_FUNCINFO',
            j_query: JSON.stringify({
              custom: [
                {
                  code: 'FUNCINFO_FUNCCODE',
                  value: state.formState.code,
                  type: '=',
                  cn: 'and',
                },
              ],
            }),
            limit: 1,
          };

          GetFuncDetail(params)
            .then((res) => {
              if (res.length === 0) {
                Modal.alert('功能不存在！');
              } else {
                state.formState.id = res[0].JE_CORE_FUNCINFO_ID;
              }
            })
            .catch((err) => {
              Modal.alert(err.message, 'error');
            });
        },
        // 点击主子传值
        getTransferValue() {
          const eleRef = ref();
          Modal.window({
            title: '主子传值',
            width: '1000px',
            height: '600px',
            okButton: {
              handler: ({ $modal }) => {
                state.formState.transferValueCode = eleRef.value.formmatData($modal);
                return false;
              },
            },
            cancelButton: true,
            content() {
              return h(MasterChildTransferValue, {
                ref: eleRef,
                records: state.formState,
                transferValueCode: state.formState.transferValueCode,
              });
            },
          });
        },
      };

      onMounted(() => {
        const { RESOURCEFIELD_CONFIGINFO } = state.formState;

        const cfgs = RESOURCEFIELD_CONFIGINFO ? RESOURCEFIELD_CONFIGINFO.split(',') : [];

        state.formState.code = cfgs[0] || '';
        state.formState.fkName = cfgs[1] || '';
        state.formState.number = cfgs[2] || '';
        state.formState.id = '';
        // 这边还需做处理，数据格式
        state.formState.transferValueCode = cfgs[3] && cfgs[4] ? `${cfgs[3]},${cfgs[4]}` : '';

        // 通过功能的 code 值获取功能的 id zhi
        state.formState.code && methods.getFuncDetail();
      });

      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style lang="less" scoped>
  .data-dictionary-high-config {
    .inputWrap {
      position: relative;
      .setIcon {
        position: absolute;
        top: 50%;
        right: 10px;
        transform: translate(0, -50%);
        cursor: pointer;
      }
    }
    .prompt {
      margin: 0 0 0 10px;
      font-size: 14px;
      color: #2a6fd0;
      vertical-align: top;
    }
  }
</style>
